//
//  ActivePowerViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/6/21.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "ActivePowerViewController.h"
#import "ShopListChooseViewController.h"
#import "BGTextView.h"
#import "PickerViewController.h"
#import <QMapKit/QMapKit.h>


@interface ActivePowerViewController ()<UITextViewDelegate,ShopListChooseDelegate,QMapViewDelegate>
{
    NSString *_latitude;
    NSString *_longitude;
}
@property (nonatomic,strong)  BGTextView*textView;
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) NSString *shopName;
@property (nonatomic,strong) NSString *shopId;

@property (nonatomic,strong) QMapView *mapView;

@end

@implementation ActivePowerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
    [self creatTextView];
    [self getNoti];
    [self initView];
    [self searchPowerFun];
    [self addNoticeForKeyboard];
}

- (void)UISetting{
    _dataArray = [NSMutableArray array];
    
    _buttonSure.layer.masksToBounds = YES;
    _buttonSure.layer.cornerRadius = 5;
    
    _labelID.text = _powerId;
    
    _labelShopName.text = @"";
    
    if (_typeValue.integerValue == 102) {
        _labelTitle.text = @"激活充电宝";
    }else{
        _labelTitle.text = @"变更充电宝";
    }

//    设备类型 1、WiFi 3、蓝牙 4、密码
    NSString *typeString;
    if (_deviceType.integerValue == 1) {
        typeString = @"WiFi";
    }else if (_deviceType.integerValue == 3){
        typeString = @"蓝牙";
    }else if (_deviceType.integerValue == 4){
        typeString = @"密码";
    }else{
        typeString = @"2G";
    }

    _textFieldDeviceType.text = [NSString stringWithFormat:@"%@类型",typeString];
}


- (void )creatTextView{
    
    _textView = [[BGTextView alloc] initWithFrame:CGRectMake(10, 210, kScreenSize.width - 20, 300-170)];
    _textView.textFont = [UIFont systemFontOfSize:15];
    _textView.placeholderStr = @"备注可留空";
    _textView.placeholderColor = kColorFrom0x(0xbebebe);
    _textView.textViewTextColor = [UIColor blackColor];
    _textView.backgroundColor = kColorFrom0x(0xf4f4f4);
    
    _textView.tintColor = [UIColor blackColor];
//    _textView.keyboardType = UIKeyboardTypeNumberPad;
    [_textView updateInfo];
    _textView.delegate = self;
    [_backView addSubview:_textView];
}


- (void)textViewDidChange:(UITextView *)textView{
    [_textView textViewDidChange:textView];
}

#pragma mark - 通知

- (void)getNoti{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shopNameSelectedByNoti:) name:@"shopNameFromPicker" object:nil];
}

- (void)shopNameSelectedByNoti:(NSNotification *)noti{
    NSDictionary *dic = noti.object;
    
    _shopName = dic[@"name"];
    _shopId = dic[@"id"];
    
    _labelShopName.text = _shopName;
}

#pragma mark - 网络请求

- (void)loadListData{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] getShopListByEid:kUserId page_size:@"1000" page_index:@"0" status:nil store_type:nil progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            
            [_dataArray removeAllObjects];
            for (NSDictionary *dic in responseBody[@"data"]) {
                ShopModel *model = [[ShopModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                if (model.status.integerValue == 1) {
                    [_dataArray addObject:model];
                }
            }
//            if (_dataArray.count > 0) {
//                ShopModel *model = _dataArray[0];
//                _labelShopName.text = model.name;
//                _shopName = model.name;
//                _shopId = model.id;
//            }
        }else{
            [self alertVCByTitle:responseBody[@"message"]];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}
//查找充电宝 用于查看充电宝名称
- (void)searchPowerFun{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] findPowerByEid:kUserId alias:_labelID.text progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            NSDictionary *dataDic = responseBody[@"data"];
            
            PowerModel *model = [[PowerModel alloc] init];
            NSDictionary *chargingDic = dataDic[@"charging"];
            if ([chargingDic class] != [NSNull class]) {
                [model setValuesForKeysWithDictionary:chargingDic];
            }
            
            ShopModel *shopModel = [[ShopModel alloc] init];
            NSDictionary *shopDic = dataDic[@"store"];
            if ([shopDic class] != [NSNull class]) {
                [shopModel setValuesForKeysWithDictionary:shopDic];
                _labelShopName.text = shopModel.name;
                _shopName = shopModel.name;
                _shopId = shopModel.id;
            }
            
            _textFieldName.text = [BGFunctionHelper isNULLOfString:model.name] ? @"" : model.name;
            
            [self loadListData];
            
        }else{
            [self alertVCByTitle:responseBody[@"message"]];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
    
}

- (void)activePowerFun{
    
    if ([BGFunctionHelper isNULLOfString:_shopId] || _shopId.integerValue == 10) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择店铺" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    
    [[AFClient shareInstance] activePowerByEid:kUserId alias:_labelID.text name:_textFieldName.text remark:_textView.text store_info_id:_shopId latitude:_latitude longitude:_longitude progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            [self alertVCByTitle:@"充电宝已激活"];
        }else{
//            kAlert(responseBody[@"message"]);
            [self alertVCByTitle:responseBody[@"message"]];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)changePowerFun{
    if ([BGFunctionHelper isNULLOfString:_shopId]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择店铺" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    
    [[AFClient shareInstance] updatePowerByEid:kUserId alias:_labelID.text name:_textFieldName.text remark:_textView.text store_info_id:_shopId progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            [self alertVCByTitle:@"充电宝信息已变更"];
        }else{
            [self alertVCByTitle:responseBody[@"message"]];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

#pragma mark - 点击事件

//返回按钮
- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

//点击保存
- (IBAction)saveButtonClick:(UIButton *)sender {
//    kAlert(@"点击保存");
//    [self backButtonClick:nil];
    if (_typeValue.integerValue == 102) {//激活充电宝
        [self activePowerFun];
    }else{
        [self changePowerFun];
    }
}

//店铺名称
- (IBAction)shopNameButtonClick:(UIButton *)sender {
    if (_dataArray.count > 0) {
        UIStoryboard *storyboard = kMainStroyboard;
        
        ShopListChooseViewController *shopListChooseVC = [storyboard instantiateViewControllerWithIdentifier:@"ShopListChooseViewController"];
        shopListChooseVC.dataArray = _dataArray;
        shopListChooseVC.delegate = self;
        [self.navigationController pushViewController:shopListChooseVC animated:YES];
        
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"暂无店铺信息" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}


- (void)alertVCByTitle:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 键盘通知
- (void)addNoticeForKeyboard {
    
    //注册键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    //注册键盘消失的通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

///键盘显示事件
- (void) keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    //计算出键盘顶端到inputTextView panel底端的距离(加上自定义的缓冲距离INTERVAL_KEYBOARD)
    CGFloat offset = (_textView.orginY + kbHeight) - (self.view.frame.size.height - kbHeight);
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

#pragma mark - shopListChooseDelegate

- (void)sendValue:(ShopModel *)model{
    _labelShopName.text = model.name;
    _shopName = model.name;
    
    NSLog(@"shopId -> %@",_shopId);
    _shopId = model.id;
    NSLog(@"shopId -> %@",_shopId);

}

#pragma mark - mapView
- (void)initView {
    _mapView = [[QMapView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    _mapView.showsUserLocation = YES;
    
    _mapView.userTrackingMode = QUserTrackingModeFollow;
    
    _mapView.showsScale = YES;
    
    [_mapView removeAnnotations:_mapView.annotations];
    
}

-(void)mapView:(QMapView *)mapView didUpdateUserLocation:(QUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    _latitude = [NSString stringWithFormat:@"%lf",userLocation.coordinate.latitude];
    _longitude = [NSString stringWithFormat:@"%lf",userLocation.coordinate.longitude];
    NSLog(@"coordinate:%f,%f, heading:%f", userLocation.coordinate.latitude, userLocation.coordinate.longitude, userLocation.heading.trueHeading);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
